package com.example.common.core.utils;

import com.example.common.core.constants.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 23050
 * @version 1.0
 * @description: TODO
 * @date 2025/2/4 21:43
 */
public class JwtUtils {

    /**
     * ⽣成令牌
     * @param claims 数据
     * @param secret 密钥
     * @return 令牌
     */
    public static String createToken(Map<String, Object> claims,
                                     String secret)
    {
        String token = Jwts.builder()
                .setClaims(claims) //载荷
                .signWith(SignatureAlgorithm.HS512, secret) //签名的算法
                .compact();
        return token;
    }

    /**
     * 从令牌中获取数据
     * @param token 令牌
     * @param secret 密钥
     * @return 数据
     */
    public static Claims parseToken(String token, String secret) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    //从jwt的载荷中获取userkey
    public static String getUserKey(Claims claims) {
        return toStr(claims, JwtConstants.LOGIN_USER_KEY);
    }
    //从jwt的载荷中获取userid
    public static String getUserId(Claims claims) {
        return toStr(claims, JwtConstants.LOGIN_USER_ID);
    }

    private static String toStr(Claims claims, String loginUser) {
        Object value = claims.get(loginUser);
        if (value == null) {
            return "";
        }
        return value.toString();
    }







    public static void main(String[] args) {
        Map<String,Object> cla = new HashMap<>();
        cla.put("testUser",132456465L);
        cla.put("test01",123);
        String token = createToken(cla, "1111111111111111111111111111111");
        System.out.println(token);

        Claims claims = parseToken(token,"1111111111111111111111111111111");
        System.out.println(claims);
    }


}
